package com.wss.lsl.test.driven.concurrent;

import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 主线程等待所有子线程结束再结束
 * 
 * @author sean
 * 
 */
public class CountDownLatchDemo {

	public static void main(String[] args) {
		int playerNumber = 100;
		CountDownLatch begin = new CountDownLatch(1);
		CountDownLatch end = new CountDownLatch(playerNumber);

		ExecutorService executorService = Executors
				.newFixedThreadPool(playerNumber);
		for (int i = 0; i < playerNumber; i++) {
			executorService.execute(new Player(begin, end));
		}
		begin.countDown();
		try {
			// 阻塞，直到所有线程结束
			end.await();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("end should be last!");
		executorService.shutdown();

	}

	static class Player implements Runnable {

		private static final Random RANDOM = new Random();
		private CountDownLatch begin;
		private CountDownLatch end;

		public Player(CountDownLatch begin, CountDownLatch end) {
			super();
			this.begin = begin;
			this.end = end;
		}

		@Override
		public void run() {
			try {
				begin.await();
				System.out.println("time: " + RANDOM.nextInt(10));
			} catch (InterruptedException e) {
				Thread.currentThread().interrupt();
			} finally {
				end.countDown();
			}

		}

	}
}
